package com.acme.service.bank.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import com.acme.domain.account.Account;
import com.acme.domain.client.Bank;
import com.acme.domain.client.Client;
import com.acme.service.bank.BankReportService;


public class BankReportServiceImpl implements BankReportService {

	@Override
	public int getNumberOfClients(Bank bank) {
		return bank.getClientsList().size();
	}

	@Override
	public int getNumberOfOpenAccounts(Bank bank) {
		List<Account> accounts = getCustomerAccounts(bank);
		int counter = 0;
		for(Account acc: accounts) {
			if(acc.isOpened())
				counter++;
		}
		return counter;
	}

	@Override
	public int getNumberOfAccounts(Bank bank) {
		Set<Client> bankClients = bank.getClientsList();
		int counter = 0;
		for(Client client: bankClients) {
			counter += client.getAccountsList().size();
		}
		return counter;
	}

	@Override
	public List<Account> getAccountsSortedByDeposit(Bank bank, boolean ascending) {
		List<Account> accounts = getCustomerAccounts(bank);
		Collections.sort(accounts, new Comparator<Account>() {
			@Override
			public int compare(Account acc1, Account acc2) {
				double acc1Balance = acc1.getBalance();
				double acc2Balance = acc2.getBalance();
				if(acc1Balance > acc2Balance) {
					return 1;
				}
				else if(acc1Balance < acc2Balance){
					return -1;
				}
				else {
					return 0;
				}
			}
		});
		return accounts;
	}

	@Override
	public List<Account> getCustomerAccounts(Bank bank) {
		Set<Client> bankClients = bank.getClientsList();
		List<Account> accounts = new ArrayList<Account>();
		for(Client client: bankClients) {
			accounts.addAll(client.getAccountsList());
		}
		return accounts;
	}
}